//
//  ST_DTChatMessageSendHander.swift
//  DrinkTogether
//
//  Created by DouLei on 2018/6/30.
//  Copyright © 2018 DouLei. All rights reserved.
//

import UIKit
import SwifterSwift
import SwiftyJSON
import SDWebImage
import NIMSDK
import SwiftyUserDefaults

var Tian_msg_pushing = false

let SENSITIVE_CODE = 10005

fileprivate var pushSet = Set<String>()

protocol ST_TianSendMessageStatusProtocol:AnyObject {
    func sendMessagePreview(message:ST_DTChatMessage)
    func sendMessageProgress(id:String,progress:Int32)
    func sendMessageFinish(id:String,error:Error?)
    /// 检查是否收到第一条消息
    func sendMessageCheckReceiveFirst()->Bool
}

class ST_DTChatMessageSendHander:NSObject {
    
//    fileprivate lazy var sourceMap = [String:Int]()
    
    fileprivate(set) lazy var sendRequreCoinMap = [String:Float]()
    
    fileprivate lazy var delegateSet:NSMapTable<NSString,AnyObject> = {
        
        let table = NSMapTable<NSString, AnyObject>.strongToWeakObjects()
        
        return table
    }()
    
    static let shared = ST_DTChatMessageSendHander()
    
    private override init() {
        super.init()
        
        NIMSDK.shared().chatManager.add(self)
    }
    
//    MARK: - Public Method
    func setObserver(sessionId:String,send_requre_coin:Float = 0,delegate:ST_TianSendMessageStatusProtocol?){
        
//        sourceMap.updateValue(source, forKey: sessionId)
        
        sendRequreCoinMap.updateValue(send_requre_coin, forKey: sessionId)
        
        if let d = delegate{
            delegateSet.setObject(d, forKey: sessionId as NSString)
        }
        
        
    }
    
//    deinit {
//        print("ST_DTChatMessageSendHander -- 释放")
//    }
    
//    weak var chatVC:ST_PrivateChatViewController?
    
    
    
    func sendMessage(message:ST_DTChatMessage)  {
        
        
//        小助手等 直接发送
        if SYSTEM_SESSION_SET.contains(message.chatID){
            
            
            let key =  message.chatID
            
            if let delegate = self.delegateSet.object(forKey: key as NSString) as? ST_TianSendMessageStatusProtocol{
//            self.append_model(message)
                delegate.sendMessagePreview(message: message)
            }
            
            self.push_msg_to_i_m_service(message: message)
            
            report_sys_helper_msg(text: message.chatText, id: message.chatID)
            
            return
        }
       
        
        var coin = self.sendRequreCoinMap[message.chatID] ?? 0
        
//        type类型(1:文字,2:图片,3:视频,4:语言，5:礼物)
        var msgType:Int?
        var msgCloudKey:String?
        switch message.cellStyle {
        case .Text:
            msgType = 1
            msgCloudKey = message.chatText
        case .Image,.snapChat:
            msgType = 2
            msgCloudKey = message.imageRemoteUrl
        case .CustomNewEmoji:
            msgType = 2
            msgCloudKey = message.emoji?.imageUrl
        case .voice:
            msgType = 4
            msgCloudKey = message.voiceRemoteUrl
        case .Video:
            msgType = 3
            msgCloudKey = message.videoUrl
        case .incomeGift:
            msgType = 5
            msgCloudKey = "礼物"
            
            if let income = message.goods?.income{
                coin = income * 10
            }
//            其他消息直接发
        default:
            
//            self.append_model(message)
            
            if let delegate = self.delegateSet.object(forKey: message.chatID as NSString) as? ST_TianSendMessageStatusProtocol{
//            self.append_model(message)
                delegate.sendMessagePreview(message: message)
            }
            
            self.push_msg_to_i_m_service(message: message)
            
            return
        }
        
        
        guard let type = msgType else { return  }
        
        let key = msgCloudKey ?? "67b605c6e2a74904244f69a02b0f21b2"
        
        
        if Tian_msg_pushing {
            return
        }
        
        Tian_msg_pushing = true
        
        
        
        if let delegate = self.delegateSet.object(forKey: message.chatID as NSString) as? ST_TianSendMessageStatusProtocol{
//            self.append_model(message)
            delegate.sendMessagePreview(message: message)
        }
        
        
        
        if message.cellStyle == .Image || message.cellStyle == .snapChat{
            
            back_thread_execute {
                
                guard let url = message.imageLocalURL, let data = try? Data.init(contentsOf: URL(fileURLWithPath: url)),let qrcodeImg = UIImage.init(data: data) else {
                    
                    self.send_msg_error(sessionId: message.chatID, uid: message.uuid, code: -12, err: "")
                    
                    return
                }
                
                
                if self.identified_as_wechat_q_r_code(qrcodeImg: qrcodeImg){
                    
                    self.send_msg_error(sessionId: message.chatID, uid: message.uuid, code: SENSITIVE_CODE, err: "")
                    
                    return
                }else{
                    
                    qrcodeImg.perform_text_recognition(completion: { (array) in
                    
                        print("识别到的文案：",array ?? "空")
                        
                        if array?.first(where: {$0.contains("微") && $0.contains("信")}) != nil {
                         
                            print("识别图片带有[微信]字样")
                            
                            self.send_msg_error(sessionId: message.chatID, uid: message.uuid, code: SENSITIVE_CODE, err: "")
                            
                        }else{
                            
                            
                            self.request_remote_check(message: message, type: type, coin: coin, words: key)
                        }
                    })
                    
                }
                
                
            }
            
                
        }else{
            
            request_remote_check(message: message, type: type, coin: coin, words: key)
        }
        
    }
    
    /// 系统消息上报
    private func report_sys_helper_msg(text:String,id:String){
        
        
        let dict = ["words":text,"target_accid":id,"type":1,"coin":0] as [String : Any]
        
        JVrequest(PH.shumeiTextPostApi,parameters:dict ,success: { (json) in
            
            print("上报小助手 json：",json)
            
        }) { (code, err) in
            
            print("上报小助手 error：",err)
            
        }
        
    }
    
    
    fileprivate func request_remote_check(message:ST_DTChatMessage,type:Int,coin:Float,words:String){
        
        let dict = ["words":words,"target_accid":message.chatID,"type":type,"coin":coin] as [String : Any]
        
        // 王航说可以删除，
        if type == 5 {
            
//            if let logGiftId = message.goods?.logGiftId{
//                dict.updateValue(logGiftId, forKey: "member_gift_id")
//            }else{
//                return
//            }
            
            Tian_msg_pushing = false
            
            self.push_msg_to_i_m_service(message: message)
            
            
            return
        }
        
        
        
        JVrequest(PH.shumeiTextPostApi,parameters:dict ,success: { (json) in
            
            Tian_msg_pushing = false
            
            self.push_msg_to_i_m_service(message: message)
            
            let data = json["data"]
            
            print("[上报黑产]正确：",data,"--是否主线程：",Thread.current.isMainThread)
            
            ST_BTUserInfoManager.shared.modify_sweet_coin(value: data["sweet_currency"].floatValue)
            
            ST_BTUserInfoManager.shared.modify_free_talk_count(value: data["free_quick_talk_num"].intValue)
            
            ST_BTUserInfoManager.shared.modify_sweet_income(value: data["income"].doubleValue, outValue: data["income"].doubleValue/10)
            
            
        }) { (code, err) in
            
            self.send_msg_error(sessionId: message.chatID,uid:message.uuid, code: code, err: err)
            
        }
        
    }
    
    
    fileprivate func send_msg_error(sessionId:String,uid:String,code:Int,err:String){
        
        main_thread_execute {
        
            Tian_msg_pushing = false
            
            if let delegate = self.delegateSet.object(forKey: sessionId as NSString) as? ST_TianSendMessageStatusProtocol{
                
                let e = NSError.init(domain: err, code: code, userInfo: nil)
                
                delegate.sendMessageFinish(id: uid, error: e)
            }
        }
        
        
        
    }
    
    
    func push_msg_to_i_m_service(message:ST_DTChatMessage){
        
        
        switch message.cellStyle {
        case .Image,.snapChat:
            self.send_image_message(message)
        case .CustomNewEmoji:
            self.send_local_emoji_message(message)
        case .voice:
            self.send_voice_message(message)
        case .Video:
            self.send_video_message(message)
        case .gif:
            self.send_local_gif_message(message)
        case .redPacket:
            self.send_red_packet_attach_message(message)
        case .redPacketReceived:
            self.send_red_packet_of_received_attach_message(message)
        case .goodsType:
            self.send_goods_message(message)
        case .likeProp,.incomeGuard,.incomeGift:
            self.send_income_goods_message(message)
        case .tips:
            self.send_tips_message(message)
        case .femaleInviteChat:
            send_female_invite_chat_message(message)
        default:
            self.send_text_message(message)
        }
        
        ST_ConversationAdapter.shared.refresh_all_data()
        
    }
    
    /**
     识别微信二维码
     */
    fileprivate func identified_as_wechat_q_r_code(qrcodeImg:UIImage)->Bool{
        
//        有微信二维码 为真
        return qrcodeImg.read_q_r_code_string().first(where: {$0.contains("wechat")}) != nil
    }
    
    
    private func message_setting_config(sessionId:String)->NIMMessageSetting{
        
        let setting = NIMMessageSetting()
        
        setting.apnsEnabled = true
        
        ///BTStrangerManager.shared.addMySendStranger(id: sessionId)
        
        return setting
        
    }
    
    private func send_female_invite_chat_message(_ message:ST_DTChatMessage){
        
        
        guard let fType = message.femaleInviteChatType else{
            return
        }
        
        let m = ST_BTFemaleInviteChatMessageModel()
        
        m.inviteType = fType
        
        let msg = message.create_send_n_i_m_message()
                
        let customObj = NIMCustomObject()
        
        customObj.attachment = m
        
        msg.messageObject = customObj
        
        msg.apnsContent = "发送了一个邀请"
        
        let setting = NIMMessageSetting()
        
        setting.apnsEnabled = true
          
        msg.setting = setting
        
        
        msg.remoteExt = message.remoteExt

        ///BTStrangerManager.shared.addMySendStranger(id: message.chatID)
        
        ST_DTChatMessageSendHander.shared.send_to_n_i_m(msg: msg, sessionId: message.chatID)
        
    }
    
    private func send_text_message(_ message:ST_DTChatMessage){
        
        if message.cellStyle != .Text{
            return
        }
        
        let msg = message.create_send_n_i_m_message()
        
        msg.text = message.chatText
        
        msg.setting = self.message_setting_config(sessionId: message.chatID)
        
        msg.apnsPayload = generate_apns_payload(alertTitle: message.chatText)
        
        msg.remoteExt = message.remoteExt
        
        send_to_n_i_m(msg: msg, sessionId: message.chatID)
            
//            self.modifyIdClosure?(message.uuid,msg.messageId)
            
          
    }
    
    
    private func send_local_emoji_message(_ message:ST_DTChatMessage){
        
        if message.cellStyle != .CustomNewEmoji{
            return
        }
        
        guard let emoji = message.emoji else { return }
        
        let msg = message.create_send_n_i_m_message()
                
        let customObj = NIMCustomObject()
        
        customObj.attachment = emoji
        
        msg.messageObject = customObj
        
        msg.apnsContent = "发送了一个表情"
        
        let setting = NIMMessageSetting()
        
        setting.apnsEnabled = true
          
        msg.setting = setting
        
        
        msg.remoteExt = message.remoteExt

        ///BTStrangerManager.shared.addMySendStranger(id: message.chatID)
        
        
        send_to_n_i_m(msg: msg, sessionId: message.chatID)
        
        
    }
    
    
    private func send_local_gif_message(_ message:ST_DTChatMessage){
        
        
        
    }
    
    
    /**
     发送提示消息
     */
    private func send_tips_message(_ message:ST_DTChatMessage){
        
        guard let t = message.customTips else { return }
        
        let msg = message.create_send_n_i_m_message()
                
        let customObj = NIMCustomObject()
        
        customObj.attachment = t
        
        msg.messageObject = customObj
        
        let setting = NIMMessageSetting()
        
        setting.apnsEnabled = false
        
        setting.shouldBeCounted = false
          
        msg.setting = setting

        ///BTStrangerManager.shared.addMySendStranger(id: message.chatID)
        
        send_to_n_i_m(msg: msg, sessionId: message.chatID)
        
    }
    
    
    /**
     新版有收益的版本
     */
    private func send_income_goods_message(_ message:ST_DTChatMessage){
        
        guard let goods = message.goods else { return }
        
        let attach = ST_Custom255AttachmentModel()
        
        /*2 :喜欢道具
         3 :新守护 有收益
         4 :新礼物 有收益
         5:搭讪礼物
        */
        if message.cellStyle == .incomeGift {
            attach.type = 4
            if goods.type == .accost{
                attach.type = 5
            }
            
            message.remoteExt.updateValue(message.goods?.income ?? 0, forKey: "income")
            
            if ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex == .male{
                message.remoteExt.updateValue(ST_BTUserInfoManager.shared.additional_attributes?.freeAccostTime ?? 0, forKey: "freeSayHiNum")
            }
            
            
        }else if message.cellStyle == .incomeGuard {
            attach.type = 3
        }else{
            attach.type = 2
        }
        
        attach.goodsId = goods.goodsId
        attach.title = goods.title
        attach.subTitle = goods.subTitle
        attach.imageUrl = goods.imageUrl
        attach.svgaUrl = goods.svgaUrl
        
        let msg = message.create_send_n_i_m_message()
                
        let customObj = NIMCustomObject()
        
        customObj.attachment = attach
        
        msg.messageObject = customObj
        
        msg.apnsContent = "发送了一个礼物"
        
        let setting = NIMMessageSetting()
        
        setting.apnsEnabled = true
          
        msg.setting = setting
        
        msg.remoteExt = message.remoteExt

        ///BTStrangerManager.shared.addMySendStranger(id: message.chatID)
        
        send_to_n_i_m(msg: msg, sessionId: message.chatID)
        
    }
    
    private func send_goods_message(_ message:ST_DTChatMessage){
        
        
        guard let goods = message.goods else { return }
        
        let msg = message.create_send_n_i_m_message()
                
        let customObj = NIMCustomObject()
        
        customObj.attachment = goods
        
        msg.messageObject = customObj
        
        msg.apnsContent = GiveGoodsApnsText(goods: goods)
        
        let setting = NIMMessageSetting()
        
        setting.apnsEnabled = true
          
        msg.setting = setting
        
        msg.remoteExt = message.remoteExt

        ///BTStrangerManager.shared.addMySendStranger(id: message.chatID)
        
        send_to_n_i_m(msg: msg, sessionId: message.chatID)
            
         
        
    }
    
    private func send_voice_message(_ message:ST_DTChatMessage){
        

        guard let localPath = message.voiceLocalPath else{return}
        
     
        
        let msg = message.create_send_n_i_m_message()
        
        msg.remoteExt = message.remoteExt
        
        msg.setting = self.message_setting_config(sessionId: message.chatID)

        let audioObj = NIMAudioObject.init(sourcePath: localPath)
        
        audioObj.duration = message.voiceDuration * 1000
        
        print("发送的 voice duration:",audioObj.duration)
        
        msg.messageObject = audioObj
        
//        self.modifyIdClosure?(message.uuid,msg.messageId)
        
        send_to_n_i_m(msg: msg, sessionId: message.chatID)
        
    }
    
    
    private func send_image_message(_ message:ST_DTChatMessage){
        
        
        guard let localPath = message.imageLocalURL else {
            return
        }
        
   
        
        let msg = message.create_send_n_i_m_message()
        
        msg.setting = self.message_setting_config(sessionId: message.chatID)
        
        
        var remoteExt = message.remoteExt
        
        if message.cellStyle == .snapChat{
            remoteExt.updateValue("true", forKey: "snapChat")
        }
        
        msg.remoteExt = remoteExt
        

        
        
        let img = NIMImageObject.init(filepath: localPath)
        
        msg.messageObject = img
        
//        self.modifyIdClosure?(message.uuid,msg.messageId)
        
        message.uploadStatus = .uploading
        
//        print("图片message 地址：",Unmanaged.passUnretained(message).toOpaque())
        
        print("【鉴黄】消息UUID=",msg.messageId)
        
        send_to_n_i_m(msg: msg, sessionId: message.chatID)
      
    }
    
//    let uploadVideoThumbnailAllProgress = 0.1
//
//    let uploadVideoAllProgress = 0.8
//
//    let uploadRongCloudAllProgress = 0.1
    
    private func send_video_message(_ message:ST_DTChatMessage){
        
        if message.cellStyle != .Video{
            return
        }
        
        let msg = message.create_send_n_i_m_message()
        
        
        
        let videoObj = NIMVideoObject.init(sourcePath: message.videoLocalPath)
        
        msg.messageObject = videoObj
        
        msg.setting = self.message_setting_config(sessionId: message.chatID)
        
        msg.remoteExt = message.remoteExt

        
       
//            self.modifyIdClosure?(message.uuid,msg.messageId)
            
            message.uploadStatus = .uploading
            
        send_to_n_i_m(msg: msg, sessionId: message.chatID)
        
    }
    
    
    
    private func send_red_packet_attach_message(_ message:ST_DTChatMessage){
        
        
        guard let attach = message.customAttachment255 else { return }
        
        let msg = message.create_send_n_i_m_message()
                
        let customObj = NIMCustomObject()
        
        customObj.attachment = attach
        
        msg.messageObject = customObj
        
        msg.apnsContent = "发送了一个红包"
        
        let setting = NIMMessageSetting()
        
        setting.apnsEnabled = true
          
        msg.setting = setting
        
        msg.remoteExt = message.remoteExt

        ///BTStrangerManager.shared.addMySendStranger(id: message.chatID)
        
        send_to_n_i_m(msg: msg, sessionId: message.chatID)
        
    }
    
    
    private func send_red_packet_of_received_attach_message(_ message:ST_DTChatMessage){
        
        
        guard let attach = message.customAttachment255 else { return }
        
        let msg = message.create_send_n_i_m_message()
                
        let customObj = NIMCustomObject()
        
        customObj.attachment = attach
        
        msg.messageObject = customObj
        
        msg.apnsContent = "对方领取了你的红包"
        
        let setting = NIMMessageSetting()
        
        setting.apnsEnabled = true
          
        msg.setting = setting
        
        msg.remoteExt = message.remoteExt

        ///BTStrangerManager.shared.addMySendStranger(id: message.chatID)
        
        send_to_n_i_m(msg: msg, sessionId: message.chatID)
    }
    
    
    func send_to_n_i_m(msg:NIMMessage,sessionId:String){
        
        
        let insertLocalMsg = {
            
            print("【华为ugly】----execute - insertLocalMsg")
            
            NIMSDK.shared().conversationManager.save(msg, for: NIMSession.init(sessionId, type: NIMSessionType.P2P), completion: { error in
              
                print("【华为ugly】----插入本地消息测试:",error ?? "正常")
                
                if error == nil{
                    
                    if let delegate = self.delegateSet.object(forKey: sessionId as NSString) as? ST_TianSendMessageStatusProtocol{
                        
                        delegate.sendMessageFinish(id: msg.messageId, error: nil)
                    }
                }
            })
        }
        
        
        let pushClosure = {
            
            print("【华为ugly】----execute - pushClosure")
            
            try? NIMSDK.shared().chatManager.send(msg, to: NIMSession.init(sessionId, type: NIMSessionType.P2P))
            
        }
        
        
        if let delegate = self.delegateSet.object(forKey: sessionId as NSString) as? ST_TianSendMessageStatusProtocol,delegate.sendMessageCheckReceiveFirst(){
            
            
            print("【华为ugly】----first msg received")
            
            pushClosure()
            
            return
            
        }
        
        
        
        TIANSession(requestUrl: PH.checkSendConfineApi, parameters: ["target_accid":sessionId]).subscribe(onNext: { res in
            
            print("【华为ugly】----json:",res)
            
            switch res {
            case .success(let json) where json["data"]["can_send"].boolValue:
        
               pushClosure()
                
            default:
                
                insertLocalMsg()
            }
            
        }).disposed(by: rx.disposeBag)
        
    }
    
    func generate_apns_payload(alertTitle:String)->[String:Any]{
        
        
        var dict = [String:Any]()
        
        guard let user = ST_BTUserInfoManager.shared.current_account_info?.userinfo else {
            return dict
        }
        
        let apsField = ["alert":["title": user.nickname+": "+alertTitle],"mutable-content":1] as [String : Any]
        
        dict.updateValue(user.avatar, forKey: "podcast-image")
        
        dict.updateValue(apsField, forKey: "apsField")
        
        return dict
    }
    
    
}


//MARK: - NIMChatManagerDelegate
extension ST_DTChatMessageSendHander:NIMChatManagerDelegate{
    
    
    func send(_ message: NIMMessage, didCompleteWithError error: Error?) {
        
        let key =  message.session?.sessionId ?? ""
        
        print("问题是 ",delegateSet.count)
        
        var reportValue = true
        
        
        if let delegate = delegateSet.object(forKey: key as NSString) as? ST_TianSendMessageStatusProtocol{
            delegate.sendMessageFinish(id: message.messageId, error: error)
            
            if delegate.sendMessageCheckReceiveFirst(){
                reportValue = false
            }
            
        }
        
        if error == nil {
            
            ST_ConversationAdapter.shared.refresh_all_data()
            
            
//            params["target_accid"] = targetAccid.toString()
//            params["is_first_send_msg"] = if(targetSendedMsg) "2" else "1"
            
            if reportValue{
                
                TIANSession(requestUrl: PH.msgSentRecordApi, parameters: ["target_accid":key,"is_first_send_msg":"1"]).subscribe(onNext: { json in
                        
                    print("【华为ugly】----json reported :",json)
                        
                }).disposed(by: rx.disposeBag)
                
            }
        
            
        
            print("发送消息成功 id:",message.messageId)
            
//            back_thread_execute {
//
//                self.postToRemote(message: message)
//
//            }
            
            guard let msg = ST_DTChatMessage.analysis(message: message) , msg.cellStyle !=  ST_DTChatCellStyle.callRecord else { return  }
            
            
            switch msg.cellStyle {
            case .Image,.snapChat:
                
                pushUrl(msg.thumbnailImageRemoteUrl ?? "", msgId: msg.uuid, sessionId: msg.chatID, api: PH.shumeiCheckImageApi)
                
            case .voice:
                
                pushUrl(msg.voiceRemoteUrl ?? "", msgId: msg.uuid, sessionId: msg.chatID, api: PH.shumeiCheckVoiceApi)
                
            case .Video:
                
                pushUrl(msg.videoUrl, msgId: msg.uuid, sessionId: msg.chatID, api: PH.shumeiCheckVideoApi)
                
            default:
                break
            }
            
            
            /*
            switch msg.cellStyle {
            case .Image,.snapChat:
                pushUrl(msg.imageRemoteUrl ?? "", msgId: msg.uuid, sessionId: msg.chatID, api: PH.shumeiCheckImageApi)
                break
            default:
                break
            }*/
            
            /// 礼物暂时不支持 领取对方的 积分
            if msg.cellStyle == .incomeGift{
                return
            }
            
            main_thread_execute {
                
                let info = ["ext":["replied":true]] as [String : Any]
                
                NotificationCenter.default.post(name: Notification.Name.i_m_message_local_ext_updated, object: nil, userInfo: info)
            }
            
        }
        
        
    }
    
    func send(_ message: NIMMessage, progress: Float) {
        
        let key =  message.session?.sessionId ?? ""

        print("问题是 ",delegateSet.count)
        
        if let delegate = delegateSet.object(forKey: key as NSString) as? ST_TianSendMessageStatusProtocol{
            
            let uploadImageProgress = Int32(progress*100)
            
            delegate.sendMessageProgress(id: message.messageId, progress: uploadImageProgress)
        }
        
    }
    
}


//MARK: - push URL to Remote
extension ST_DTChatMessageSendHander{
    
    
    fileprivate func pushUrl(_ url:String,msgId:String,sessionId:String,api:String){
        
        JVrequest(api,parameters: ["url":url,"bt_id":msgId,"target_accid":sessionId]) { (json) in
            print("【鉴黄】发送之后推送到服务器:",json)
        } failure: { (code, err) in
            print("【鉴黄】发送之后推送到服务器 error:",err)
        }

    }
}


//MARK: - send message to remote service
extension ST_DTChatMessageSendHander{
    
    /*
//    原始版本
    fileprivate func postToRemote(message: NIMMessage){

        
        if SYSTEM_SESSION_SET.contains(message.session?.sessionId ?? "23048302"){
            return
        }
       
        
        guard let msg = ST_DTChatMessage.analysis(message: message) else{
            return
        }
        
        
        var coin = self.sendRequreCoinMap[message.session?.sessionId ?? ""] ?? 0
        
//        type类型(1:文字,2:图片,3:视频,4:语言，5:礼物)
        var msgType:Int?
        var msgCloudKey:String?
        switch msg.cellStyle {
        case .Text:
            msgType = 1
            msgCloudKey = msg.chatText
        case .Image,.snapChat:
            msgType = 2
            msgCloudKey = msg.imageRemoteUrl
        case .CustomNewEmoji:
            msgType = 2
            msgCloudKey = msg.emoji?.imageUrl
        case .voice:
            msgType = 4
            msgCloudKey = msg.voiceRemoteUrl
        case .Video:
            msgType = 3
            msgCloudKey = msg.videoUrl
        case .incomeGift:
            msgType = 5
            msgCloudKey = "礼物"
            
            if let income = message.remoteExt?["income"] as? Float{
                coin = Int(income * 10)
            }
            
        default:
            return
        }
        
        if pushSet.contains(msg.uuid){
            return
        }

        pushSet.update(with: msg.uuid)
        
        
        print("发送消息成功 id:",msg.uuid,"--发树莓")
        
        guard let type = msgType else { return  }
        
        let key = msgCloudKey ?? "67b605c6e2a74904244f69a02b0f21b2"
        
        JVrequest(PH.shumeiTextPostApi,parameters:["words":key,"target_accid":msg.chatID,"type":type,"coin":coin] ,success: { (json) in
            
            
            
            let data = json["data"]
            
            print("[上报黑产]正确：",data)
            
            ST_BTUserInfoManager.shared.modify_sweet_coin(value: data["sweet_currency"].floatValue)
            
            ST_BTUserInfoManager.shared.modify_free_talk_count(value: data["free_quick_talk_num"].intValue)
            
            ST_BTUserInfoManager.shared.modify_sweet_income(value: data["income"].doubleValue, outValue: data["income"].doubleValue/10)
            
            
        }) { (code, err) in
            
            print("[上报黑产]错误：",err)
        }
        
        
        
    }
    */
    
}
